<template>
  <div class="oss-upload" :class="{'size-mini': option.size === 'mini'}">
    <el-upload
        ref="imgUpload"
        action="string"
        accept="image/jpeg,image/png,image/gif"
        class="avatar-uploader"
        :disabled="isDisabled"
        :class="{'limit': limited && uploadItem.length === limited}"
        :http-request="uploadDriverLicenseImg"
        list-type="picture-card"
        :before-upload="beforeAvatarUpload"
        :limit="limited"
        :show-file-list="true"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :file-list="showList"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
      <label class="el-upload-list__item-status-label">
        <i class="el-icon-upload-success el-icon-check" />
      </label>
      <label>{{ uploadItem.text }}</label>
    </el-upload>
    <el-dialog class="dialog-center dialog-scroll-y" :visible.sync="dialogVisible" width="50%" :modal="false">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { v4 as uuidv4 } from 'uuid';

const env = process.env
export default {
  name: 'OssUpload',
  props: ['type', 'limit', 'customVal', 'notMust', 'echodisplaylist', 'disabled', 'size'],
  data() {
    return {
      limited: this.limit || 1,
      imgValue: '',
      uploadItem: [],
      driverLicenseImg: [],
      dialogImageUrl: '',
      dialogVisible: false,
      showList: [],
      option: {
        size: this.size
      }
    }
  },
  computed: {
    isDisabled: function() {
      return this.disabled
    },
    isNotMust: function() {
      return this.notMust
    }
  },
  watch: {
    echodisplaylist: function(val) {
      this.showList = []
      if (val && val.length > 0){
        this.showList = val
        this.uploadItem = val
      }
    }
  },
  mounted: function() {
    this.showList = []
    if( this.echodisplaylist && this.echodisplaylist.length > 0 ){
      this.uploadItem = this.echodisplaylist
      this.showList = this.echodisplaylist
    }

  },
  methods: {
    beforeAvatarUpload(file) {
      const isRightFormat = (file.type === 'image/jpeg' || file.type === 'image/png')
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isRightFormat) {
        this.$message.error('照片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt10M) {
        this.$message.error('照片大小不能超过 10M!')
      }
      return isRightFormat && isLt10M
    },
    uploadDriverLicenseImg: function(item) {
      item.objKey = uuidv4() + item.file.name.substring(item.file.name.lastIndexOf('.'))
      this.uploadItem.push(item)
      const driverLicenseImg = []
      this.uploadItem.forEach((e) => {
        /*if(){
          driverLicenseImg.push(window.URL.createObjectURL(e.file))
        }*/
      })
      this.driverLicenseImg = driverLicenseImg
      this.$emit('imgChange', this.uploadItem)
    },
    handleRemove(file) {
      this.uploadItem = this.uploadItem.filter((item) => {
        return item.file !== file.raw
      })
      const driverLicenseImg = []
      this.uploadItem.forEach((e) => {
        driverLicenseImg.push(URL.createObjectURL(e.file))
      })
      console.log('删除删除', file)
      this.driverLicenseImg = driverLicenseImg
      this.$emit('imgChange', this.uploadItem)
    },
    timestamp:function(){
      const time = new Date();
      const y = time.getFullYear();
      const m = time.getMonth()+1;
      const d = time.getDate();
      const h = time.getHours();
      const mm = time.getMinutes();
      const s = time.getSeconds();
      const ms = time.getMilliseconds()
      return ""+y+this.Add0(m)+this.Add0(d)+this.Add0(h)+this.Add0(mm)+this.Add0(s)+this.Add0(ms);
    },
    // 删除图片
    removeAll() {
      this.$refs['imgUpload'].clearFiles()
      this.uploadItem = []
      this.driverLicenseImg = []
      this.dialogImageUrl = ''
      this.$emit('imgChange', [])
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    upload(value) {
      const self = this
      if (self.uploadItem.length < 1 && !self.isNotMust) {
        this.$message.warning('请选择上传图片')
        return false
      }
      if (self.uploadItem.length === 0) {
        self.$emit('success', [])
        return true
      }
      if (!self.type) {
        this.$message.error('无效业务类型')
        return false
      }
      const host = 'localhost:8000'
      // let userInfo = self.getLogonUserInfo();
      let customValStr = JSON.stringify(self.customVal || {}).replace(/^\{(.*)\}$/, '$1')
      customValStr = customValStr ? customValStr + ',' : ''
      if (!env.DUMMY) {
        self.$http.post('/file/credential', { type: self.type })
            .then(function(res) {
              const co = require('co')
              const OSS = require('ali-oss')
              const accessData = res.data.credentials
              const client = new OSS({
                region: res.data.region,
                accessKeyId: accessData.accessKeyId,
                accessKeySecret: accessData.accessKeySecret,
                stsToken: accessData.securityToken,
                bucket: res.data.bucket
              })
              const imgHost = res.data.host
              const bucketName = res.data.objectKey
              self.imgValue = imgHost + bucketName
              const loadinginstace = self.$loading({ lock: true, text: '加载中...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.0)' })
              co(function * () {
                const queryRequestList = []
                const returnParams = []
                let index = 1
                for (const item of self.uploadItem) {
                  if (item.objKey) {
                    const objKey = bucketName + item.objKey
                    const url = client.signatureUrl(objKey)
                    yield client.multipartUpload(objKey, item.file, {
                      progress: function(p, cpt) {
                        console.log(p)
                        console.log(cpt)
                      }
                      /* callback: {
                        url: host + '/file/callback',
                        host: 'oss.cn-shenzhen.aliyuncs.com',
                        body: "{" + customValStr + "\"index\":\"" + index + "\",\"token\":\"" + /!*userInfo.token +*!/ "\",\"type\":\"" + self.type + "\",\"format\":${imageInfo.format},\"width\":${imageInfo.width},\"height\":${imageInfo.height},\"etag\":${etag},\"object\":${object},\"bucket\":${bucket},\"mimeType\":${mimeType},\"size\":${size}}",
                        contentType: 'application/json',
                        // customValue: {
                        //   'x:token': userInfo.token,
                        //   'x:type': item.file.type
                        // }
                      }*/
                    }).then(function(res) {
                      console.log('success11111', res)
                    }).catch(function(error) {
                      self.$message.error('上传失败，请重新上传')
                      console.log('error11111', error)
                    })
                    /* let result = client.multipartUpload(objKey, item.file, {
                      progress: function* (p, checkpoint, res) {
                        console.log('Progress: ', p)
                        if (p === 1) {

                        }
                      },
                      callback: {
                        url: host + '/file/callback',
                        host: 'oss.cn-shenzhen.aliyuncs.com',
                        body: "{" + customValStr + "\"index\":\"" + index + "\",\"token\":\"" + /!*userInfo.token +*!/ "\",\"type\":\"" + self.type + "\",\"format\":${imageInfo.format},\"width\":${imageInfo.width},\"height\":${imageInfo.height},\"etag\":${etag},\"object\":${object},\"bucket\":${bucket},\"mimeType\":${mimeType},\"size\":${size}}",
                        contentType: 'application/json',
                        // customValue: {
                        //   'x:token': userInfo.token,
                        //   'x:type': item.file.type
                        // }
                      }
                    })*/
                    /*const param = {
                      type: self.type,
                      object: objKey,
                      url: imgHost + objKey,
                      index: index,
                      ...self.customVal
                    }*/
    /*                const reqTemp = self.$http.post('/file/query', param)
                        .then(function(res) {
                          const data = res.data || {}
                          if (data.code === '0000') {
                            console.log('======================sueee==================2')
                            // self.$emit('success', [param])
                          } else {
                            self.$message.error('上传失败，请重新上传')
                          }
                        }).catch(function(error) {
                          console.log(error)
                          self.$message.error('上传失败，请重新上传')
                        })*/
                    /*returnParams.push(param)
                    queryRequestList.push(reqTemp)*/
                  }
                  index++
                }
                Promise.all(queryRequestList).then((res) => {
                  self.$emit('success', returnParams)
                }).catch((err) => {
                  self.$message.error('上传失败，请重新上传')
                })
                loadinginstace.close()
              }).catch(function(err) {
                loadinginstace.close()
                self.$message.error('上传失败，请重新上传')
                console.log(err)
              })
            })
            .catch(function(error) {
              console.log(error)
              self.$message.error('上传失败，请重新上传')
            })
      } else {
        self.$emit('success', {
          type: 'dummy',
          object: '****.jpg'
        })
      }
    }
  }
}
</script>

<style lang="scss">
.oss-upload {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 0px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .el-upload-list--picture-card .el-upload-list__item {
    overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 0px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0 0px 0px 0;
  }
  .avatar-uploader.limit .el-upload--picture-card{
    display: none;
  }
  .avatar-uploader .el-upload-list--picture-card .el-upload-list__item-actions {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .avatar-uploader .el-upload-list--picture-card .el-upload-list__item-actions span+span {
    margin-left: 5px;
  }
  .avatar-uploader .el-upload-list--picture-card .el-upload-list__item-actions .el-upload-list__item-delete {
    font-size: 16px;
  }
  .avatar-uploader .el-upload-list--picture-card .el-upload-list__item-actions span {
    font-size: 16px;
  }
}
.oss-upload.size-mini {
  .avatar-uploader .avatar {
    width: 50px;
    height: 50px;
  }
  .avatar-uploader .el-upload--picture-card{
    width: 50px;
    height: 50px;
    line-height: 50px;
  }
  .avatar-uploader .avatar-uploader-icon {
    font-size: 20px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
  .el-upload-list--picture-card .el-upload-list__item {
    width: 50px;
    height: 50px;
  }
}
</style>
